// pages/location/location.js
const { apiHost } = require('../../common/services/hosts.js')
var amapFile = require('../../libs/amap-wx.js');
const app = getApp()
const { imageHash, Ubt, Geohash, API, Cart, User } = app.services

let timer

Page({
  data: {
    imageHash,
    focus: false,
    searchString: '',
    locatedFail: false,
    locating: true,
    addresslList: {},
    poi: null,
    citycode: '',
    searched: false,
    locations: [],
    nearbyAddress: []

  },
  bindKeyInput: function (e) {

    clearTimeout(timer)
    timer = setTimeout(() => {
      this.searchAddress()
    }, 700)
    this.setData({
      searchString: e.detail.value
    })
  },
  onLoad: function (options) {
    // 首先获取用户的位置
    // this.setData({
    //   showUserAddresses: options.show_user_addresses && !User.loadSync()
    // })
    //
    // if (this.data.showUserAddresses) {
    //   addressService.load({
    //     token: User.data.token
    //   }).then(res => {
    //     const userAddresses = res.addresses.map(address => {
    //
    //       const [lat, lon] = Geohash.decode(address.geohash || address.st_geohash)
    //       address.latitude = lat
    //       address.longitude = lon
    //       return address
    //     })
    //     this.setData({ userAddresses })
    //   })
    // }
  },

  onShow: function() {
    this.reLocate(true)

  },

  onUnload: function () {
    clearTimeout(timer)
  },

  reLocate: function (firstLoad) {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          geohash: Geohash.encode(res.latitude, res.longitude),
          latitude: res.latitude,
          longitude: res.longitude,
        })

        this.getCurrentPosition()
      },
      fail: () => {
        if (firstLoad !== true) {
          return wx.openSetting({
            success: res => {
              if (res.authSetting && res.authSetting['scope.userLocation']) {
                this.reLocate(true)
              }
            }
          })
        }
        this.setData({
          locatedFail: true,
          locating: false
        })
        wx.showToast({
          title: '没能获取到您的位置',
          mask: true
        })
      }
    })
  },

  getCurrentPosition: function () {
    var that=this
    var myAmapFun = new amapFile.AMapWX({ key: '7f364fe9a3197eddca28f522af27a527' });
    this.setData({
      locating:true
    })
    API.getGeohashPosition(this.data)
      .then(res => {
        if (res.data.status === 'success') {
          var location = res.data.result.pois[0].location
          var latitude
          var longitude
          if(location.indexOf(',')>0){

            longitude = location.substr(0,location.indexOf(','))||''
            latitude =  location.substr(location.indexOf(',')+1)||''
          }
          that.setData({
            latitude:latitude,
            longitude:longitude,
            citycode: res.data.result.addressComponent.citycode,
            poi: { name: res.data.result.pois[0].name},
            locatedFail: false,
            locating: false
          });
          myAmapFun.getInputtips({
            keywords:res.data.result.formatted_address,
            city: res.data.result.addressComponent.citycode,
            success: function (data) {
              if (data && data.tips) {
                that.setData({
                  nearbyAddress: data.tips,
                });
              }
            }
          })


        } else {
          this.setData({
            locatedFail: true,
            locating: false
          })
        }
      })
      .catch(() => {
        this.setData({
          locatedFail: true,
          locating: false
        })
      })

  },
  searchAddress: function () {
    var that = this
    var keywords = that.data.searchString
    var myAmapFun = new amapFile.AMapWX({ key: '7f364fe9a3197eddca28f522af27a527' });
    myAmapFun.getInputtips({
      keywords: keywords,
      city: that.data.citycode,
      success: function (data) {
        if (data && data.tips) {
          that.setData({
            nearbyAddress: data.tips
          });
        }
      }
    })



    // 修复city_id可能不存在导致的报错
    // if (this.data.poi && this.data.searchString) {
    //   API.searchAddress({
    //     city: this.data.citycode,
    //     address: this.data.searchString,
    //   })
    //   .then(res => {
    //     if (res.data.status === 'success') {
    //       if (res.data.result.pois) {
    //         var pois = res.data.result.pois
    //         var locations = new Array(pois.length)
    //         locations[0] ={
    //           address: res.data.result.addressComponent.province + res.data.result.addressComponent.city + res.data.result.addressComponent.district + res.data.result.addressComponent.streetNumber.street + res.data.result.addressComponent.streetNumber.number,
    //           name: res.data.result.formatted_address,
    //           geohash: res.data.result.addressComponent.streetNumber.location
    //         }
    //         for (var i=1;i<pois.length;i++) {
    //           locations[i] = {
    //             geohash: pois[i].location,
    //             name: pois[i].name,
    //             address: pois[i].address
    //           }
    //         }
    //         this.setData({
    //           locations: locations
    //         })
    //       }
    //     }
    //   })
    // }
  },
  selectAddress: function (e) {
    const previousPage = getCurrentPages().splice(-2, 1)[0]
    if (previousPage && /pages\/address\//.test(previousPage.__route__)) {
      wx.setStorage({
        key: 'TEMPORARY_SELECTED_DELIVER_ADDRESS',
        data: {
          address: e.currentTarget.dataset.address + e.currentTarget.dataset.name,
          longitude: e.currentTarget.dataset.geohash.split(',')[0],
          latitude: e.currentTarget.dataset.geohash.split(',')[1]
        },
        success: () => {
          wx.navigateBack()
        }
      })
    } else {
      wx.setStorageSync('FROM_LOCATION_BACK', true)
      var num = e.currentTarget.dataset.geohash.split(",");
      var place = {
        latitude: num[1],
        longitude: num[0],
        geohash: e.currentTarget.dataset.geohash,
        address: e.currentTarget.dataset.address,
        name: e.currentTarget.dataset.name
      }
      wx.setStorage({
        key: 'PLACE',
        data: place,
        success: () => {
          wx.navigateBack()
        },
        fail: (err) => {
          console.log('selectAddress err::', err)
        }
      })
    }
  },
  selectUserAddress: function ({ currentTarget }) {
    wx.setStorageSync('FROM_LOCATION_BACK', true)
    wx.setStorage({
      key: 'PLACE',
      data: currentTarget.dataset,
      success: () => {
        wx.navigateBack()
      },
      fail: (err) => {
        console.log('selectUserAddress err::', err)
      }
    })
  },
  useLocatedPlace: function () {
    const previousPage = getCurrentPages().splice(-2, 1)[0]
    if (previousPage && /pages\/address\//.test(previousPage.__route__)) {
      var addresses = this.data.poi.address==undefined?'':this.data.poi.address
      wx.setStorage({
        key: 'TEMPORARY_SELECTED_DELIVER_ADDRESS',
        data: {
          latitude:this.data.latitude,
          longitude:this.data.longitude,
          address: addresses + this.data.poi.name,
          geohash: this.data.poi.geohash,
          st_geohash: this.data.poi.geohash
        },
        success: () => {
          wx.navigateBack()
        }
      })

    } else {
      wx.setStorageSync('FROM_LOCATION_BACK', true)
      wx.setStorage({
        key: 'PLACE',
        data: {
          latitude:this.data.latitude,
          longitude:this.data.longitude,
          address: this.data.poi.name,
          geohash: this.data.poi.geohash,
          st_geohash: this.data.poi.geohash
        },
        success: () => {
          wx.navigateBack()
        },
        fail: (err) => {
          console.log('useLocatedPlace err::', err)
        }
      })
    }
  }
})
